#include "FileTableView.h"
#include <QtGui/QResizeEvent>
#include "ContextMenuTrigger.h"
#include "FileTableModel.h"

FileTableView::FileTableView(QWidget *parent)
: QTableView(parent),_contextMenu(0)
{	
	new ContextMenuTrigger(this->viewport());
}

FileTableView::~FileTableView()
{

}

QMenu* FileTableView::contextMenu() const{
	return _contextMenu;
}

void FileTableView::resizeEvent ( QResizeEvent * evt ){
	QTableView::resizeEvent(evt);
	if (evt->size(). width ()!=evt->oldSize().width()){
		emit scrollViewWidthChanged(evt->size().width());
	}
}

QString FileTableView::currentImageFile() const{
	if (this->currentIndex().isValid()){
		return this->model()->data(this->currentIndex(),FileTableModel::FilePathRole).toString();
	}else{
		return QString::null;
	}
}

void FileTableView::setCurrentImageToNext(){
	QModelIndex currIdx=this->currentIndex();
	if (!currIdx.isValid())
		return ;

	int row=currIdx.row();
	int col=currIdx.column();
	if (++col>=this->model()->columnCount()){
		col=0;
		if (++row>this->model()->rowCount()){
			return;
		}
	}
	this->setCurrentIndex(currIdx.sibling(row,col));
	emit currentImageFileChanged(currentImageFile());
}

void FileTableView::setCurrentImageToPrev(){
	QModelIndex currIdx=this->currentIndex();
	if (!currIdx.isValid())
		return ;

	int row=currIdx.row();
	int col=currIdx.column();
	if (--col<0){
		col=this->model()->columnCount()-1;
		if (--row<0){
			return;
		}
	}
	this->setCurrentIndex(currIdx.sibling(row,col));
	emit currentImageFileChanged(currentImageFile());
}

void FileTableView::setContextMenu(QMenu* menu){
	_contextMenu=menu;
}

void FileTableView::showContextMenu(const QPoint & pos){
	if(!_contextMenu)
		return;
	_contextMenu->exec(this->mapToGlobal(pos));
}

void FileTableView::contextMenuEvent ( QContextMenuEvent * event) {
	showContextMenu(event->pos());
}

